/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.correct;

import com.wtkj.vo.dzzf.base.kfwd.CardInfo;
import com.wttech.dzzf.process.dao.DataInitilizingDao;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * 纠正错误卡片Userid
 * @author MaShibo
 * @date 2017/12/14.
 */
@Service
public class CorrectErrorCardUserId {

	private static final Logger LOGGER = LoggerFactory.getLogger(CorrectErrorCardUserId.class);

	@Resource
	private DataInitilizingDao dataInitilizingDao;

	@Resource
	private ThreadPoolTaskExecutor executor;


	private void process(){
		while (true){
			List<String> cardIds = dataInitilizingDao.queryCardIds();
			if (CollectionUtils.isEmpty(cardIds)){
				return;
			}
			List<Future<Void>> futures = new ArrayList<>(cardIds.size());
			cardIds.forEach(cardId -> futures.add(executor.submit(()->{
				processCardId(cardId);
				return null;
			})));
		}
	}

	private void processCardId(String cardId){
		LOGGER.info("处理{}中...", cardId);
		try {
			CardInfo cardInfo = dataInitilizingDao.queryCardInfoByNo(cardId.substring(4));
			String userId = cardInfo.getUserId();
			if (StringUtils.isEmpty(userId)){
				LOGGER.info("卡片【{}】的userId为空", userId);
			}
			dataInitilizingDao.updateCardInfoUserId(cardId, userId);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		CorrectErrorCardUserId service = context.getBean(CorrectErrorCardUserId.class);
		service.process();
	}
}
